<?php
/**
 * 权限路由控制器
 * User: xuyiping（xuyiping@liangzihuzhu.com.cn）
 * Date: 2017/11/27
 * Time: 13:44
 */

namespace App\Http\Controllers\Admin\system;

use App\Http\Controllers\Controller;
use App\Model\User\PermissionGroupModel;
use Illuminate\Http\Request;
use App\Model\User\PermissionModel;

class PermissionController extends  Controller
{
    public function index(){

        $groups = PermissionGroupModel::all()->toArray();

        return view('Admin/system/permission/index')->with('groups',json_encode($groups));

    }

    /**
     * ajax查询权限组列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function search(Request $request)
    {

        $where = [];

        //查询条件
        if ($request->input('permissionName')) {
            $where['permissionName'] = $request->input('permissionName');
        }

        if ($request->input('searchPermissionGroupID')) {
            $where['permissionGroupID'] = $request->input('searchPermissionGroupID');
        }

        $groups = PermissionModel::where($where)
            ->orderBy($request->input('sort'), $request->input('order'))
            ->paginate($request->input('limit'))
            ->toArray();

        //返回数组
        $res_data = array(
            'total' => $groups['total'],
            'rows' => array()
        );

        foreach ( $groups['data'] as &$row ) {

            $operation = '<a href="javascript: void(0);" onclick="Permission.del(\'' . $row['uuid'] . '\');">删除</a>&nbsp&nbsp';
            $operation .= '<a href="javascript: void(0);" onclick="Permission.edit(\'' . $row['uuid'] . '\');">修改</a>&nbsp&nbsp';

            $res_data['rows'][] = array(
                'operation'             =>   $operation,
                'permissionID'             =>   $row['permissionID'],
                'permissionName'            =>   $row['permissionName'],
                'shortName'            =>   $row['shortName'],
                'permissionGroupName'    =>   $row['permissionGroupName'],
                'permissionRequest'    =>   $row['permissionRequest'],
                'sort'    =>   $row['sort']
            );
        }

        return response()->json($res_data);
    }


    /**
     * 新增或修改权限组信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $msg = '';

        //验证单子
        if(empty($request->input('permissionGroupID'))){
            $msg .= '没有选择权限组<br>';
        }

        if(empty($request->input('permissionID'))){
            $msg .= '权限号没有填写<br>';
        }

        if( !is_numeric($request->input('permissionID')) ){
            $msg .= '权限号必须是数字<br>';
        }

        if(empty($request->input('permissionName'))){
            $msg .= '权限名称没有填写<br>';
        }

        if(empty($request->input('shortName'))){
            $msg .= '权限简称没有填写<br>';
        }

        if(empty($request->input('sort'))){
            $msg .= '权限序号没有填写<br>';
        }

        if(empty($request->input('permissionRequest'))){
            $msg .= '权限路径没有填写<br>';
        }

        if($msg){
            return response()->json([
                'code' => 400,
                'message' => $msg
            ]);
        }

        //  新增|编辑
        if ( $uuid = $request->input('uuid') ) {   // 编辑
            $permission = PermissionModel::where('uuid',$uuid )->first();

        } else {
            //  检查数据重复性
            if( $check_data = PermissionModel::where('permissionID', $request->input('permissionID') )->first() ){
                return response()->json([
                    'code' => 400,
                    'message' => '数据已存在'
                ]);
            }else{   // 新增
                $permission = new PermissionModel();

                $permission->uuid = makeUuid();
                $permission->timeStamp = date('Y-m-d H:i:s');
                $permission->createTime = date('Y-m-d H:i:s');
                $permission->creator = session('ADMIN_USER_ID');
                //权限加1
                $permission_group = PermissionGroupModel::where('group_id',$request->input('permissionGroupID'))->first();
                $permission_group->permission_num ++ ;
                $permission_group->save();

            }
        }

        $permission->permissionID = $request->input('permissionID');
        $permission->permissionName = $request->input('permissionName');
        $permission->shortName = $request->input('shortName');
        $permission->sort = $request->input('sort');
        $permission->permissionRequest = $request->input('permissionRequest');
        $permission->permissionGroupID = $request->input('permissionGroupID');
        $permission->permissionGroupName = $request->input('permissionGroupName');
        $permission->permissionType = $request->input('permissionType');
        $permission->save();

        return response()->json([
            'code' => 200,
            'message' => 'ok'
        ]);

    }

    /**
     * 查询权限数据
     * @param int $uuid 权限
     * @return \Illuminate\Http\JsonResponse
     */
    public function get($uuid)
    {

        $permission = PermissionModel::where('uuid',$uuid )->first();

        if ($permission) {
            return response()->json([
                'code' => 200,
                'message' => 'ok',
                'data' => $permission
            ]);
        } else {
            return response()->json([
                'code' => 404,
                'message' => '权限信息没有找到'
            ]);
        }

    }

    /*
     *  删除权限
     * @param int $uuid 权限
     */
    public function delete($uuid)
    {

        $permission = PermissionModel::where('uuid',$uuid )->first();

        // 权限减1
        $permission_group = PermissionGroupModel::where('group_id',$permission->permissionGroupID)->first();
        $permission_group->permission_num -- ;
        $permission_group->save();
        $permission->delete();

        return response()->json([
            'code' => 200,
            'message' => 'ok'
        ]);

    }

    //权限不足
    public function out(){

        return view('Admin/error/permission');
    }
}